define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: () => {
            const { reactive, onMounted } = Vue
            const { ElMessageBox } = ElementPlus
            const index = {
                setup() {
                    const state = reactive({
                        data: [],
                        order: '',
                        sort: '',
                        filter: {
                            drawer: false,
                            data: {
                                type: 'all',
                                keyword: '',
                            },
                            tools: {
                                keyword: {
                                    type: 'tinput',
                                    label: '查询内容',
                                    placeholder: '请输入查询内容',
                                    value: '',
                                },
                            },
                            condition: {},
                        }
                    })
                    const type = reactive({
                        data: {
                            type: [{
                                name: '全部',
                                type: 'all',
                            },
                            {
                                name: '充值套餐',
                                type: 'recharge',
                            },
                            {
                                name: 'vip套餐',
                                type: 'vip',
                            }],
                        }
                    })

                    function getData() {
                        let tempSearch = JSON.parse(JSON.stringify(state.filter.data));
                        let search = composeFilter(tempSearch, {
                            keyword: 'like',
                        });
                        Fast.api.ajax({
                            url: 'sum/trade/rule',
                            type: 'GET',
                            data: {
                                page: pagination.page,
                                list_rows: pagination.list_rows,
                                order: state.order,
                                sort: state.sort,
                                ...search,
                            },
                        }, function (ret, res) {
                            state.data = res.data.data
                            pagination.total = res.data.total
                            return false
                        }, function (ret, res) { })
                    }

                    function onChangeSort({ prop, order }) {
                        state.order = order == 'ascending' ? 'asc' : 'desc';
                        state.sort = prop;
                        getData();
                    }
                    function onOpenFilter() {
                        state.filter.drawer = true
                    }
                    function onChangeFilter() {
                        pagination.page = 1
                        getData()
                        state.filter.drawer && (state.filter.drawer = false)
                    }

                    const pagination = reactive({
                        page: 1,
                        list_rows: 10,
                        total: 0,
                    })
                    function onChangeTab() {
                        pagination.page = 1
                        getData()
                    }
                    const batchHandle = reactive({
                        data: [],
                    })
                    function onChangeSelection(val) {
                        batchHandle.data = val
                    }
                    function onBatchHandle(type) {
                        let ids = []
                        batchHandle.data.forEach((item) => {
                            ids.push(item.id)
                        })
                        switch (type) {
                            case 'delete':
                                ElMessageBox.confirm('此操作将删除, 是否继续?', '提示', {
                                    confirmButtonText: '确定',
                                    cancelButtonText: '取消',
                                    type: 'warning',
                                }).then(() => {
                                    onDelete(ids.join(','))
                                });
                                break;
                            default:
                                Fast.api.ajax({
                                    url: `sum/trade/rule/edit/id/${ids.join(',')}`,
                                    type: 'POST',
                                    data: {
                                        status: type
                                    }
                                }, function (ret, res) {
                                    getData()
                                }, function (ret, res) { })
                                break;
                        }
                    }

                    function onAdd() {
                        Fast.api.open("sum/trade/rule/add?type=add", "添加", {
                            callback() {
                                getData()
                            }
                        })
                    }
                    function onEdit(id) {
                        Fast.api.open(`sum/trade/rule/edit?type=edit&id=${id}`, "编辑", {
                            callback() {
                                getData()
                            }
                        })
                    }
                    function onDelete(id) {
                        Fast.api.ajax({
                            url: `sum/trade/rule/delete/id/${id}`,
                            type: 'DELETE',
                        }, function (ret, res) {
                            getData()
                        }, function (ret, res) { })
                    }

                    function onCommand(item) {
                        Fast.api.ajax({
                            url: `sum/trade/rule/edit/id/${item.id}`,
                            type: 'POST',
                            data: {
                                is_recommend: item.type
                            }
                        }, function (ret, res) {
                            getData()
                        }, function (ret, res) { })
                    }

                    onMounted(() => {
                        getData()
                    })

                    return {
                        state,
                        type,
                        getData,
                        onChangeSort,
                        onChangeTab,
                        onOpenFilter,
                        onChangeFilter,
                        pagination,
                        batchHandle,
                        onChangeSelection,
                        onBatchHandle,
                        onAdd,
                        onEdit,
                        onCommand,
                        onDelete
                    }
                }
            }
            createApp('index', index);
        },
        add: () => {
            Controller.form();
        },
        edit: () => {
            Controller.form();
        },
        form: () => {
            const {nextTick, ref, reactive,onBeforeMount, onMounted, getCurrentInstance,computed  } = Vue

            const addEdit = {
                setup() {
                    const { proxy } = getCurrentInstance();

                    const state = reactive({
                        type: new URLSearchParams(location.search).get('type'),
                        status: new URLSearchParams(location.search).get('status'),
                        id: new URLSearchParams(location.search).get('id')
                    })
                    const language=reactive({
                        option:[],
                        // 支持多语言的字段
                        field:['title'],
                        // field_key 用于动态获取当前编辑字段选择的语言key 0即默认的第一个
                        field_key:{
                            title:0,
                        }
                    })
                    const form = reactive({
                        model: {
                            type: 'recharge',
                            title: '',
                            price: 0.00,
                            score: 0,
                            days: 0,
                            weigh: '',
                            status: 'normal',
                        },
                        rules: {
                        },
                    })
                    const modelTitle = computed({
                        // getter
                        get() {
                            if (language.field_key.title==0) {
                                return form.model.title;
                            } else {
                                let lang_slug = language.option[language.field_key.title].slug;
                                return form.model.lang_data[lang_slug].title;
                            }
                        },
                        // setter
                        set(newValue) {
                            if (language.field_key.title==0) {
                                form.model.title=newValue;
                            }
                            //这里不和上一个if做else判断了，使lang_data额外存一份默认的语言
                            let lang_slug = language.option[language.field_key.title].slug;
                            form.model.lang_data[lang_slug].title=newValue;
                        }
                    })

                    function getLanguageOption() {
                        Fast.api.ajax({
                            url: 'sum/config/language',
                            type: 'GET',
                        }, function (ret, res) {
                            language.option = res.data.option
                            if(state.type == 'add'){//只有创建的时候 初始化多语言对象。编辑的时候用获取到的数据。不加限制的话，编辑时会出现偶发的空对象覆盖获取到的数据
                                language.option.forEach(lang_option => {
                                    form.model.lang_data[lang_option.slug] = {};
                                    // 为每个语言对象添加 language.field 数组中的字段
                                    language.field.forEach(lang_field => {
                                        form.model.lang_data[lang_option.slug][lang_field] = '';  // 可以根据需要设置默认值
                                    });
                                });
                            }
                            return false
                        }, function (ret, res) { })
                    }

                    function getDetail() {
                        Fast.api.ajax({
                            url: `sum/trade/rule/detail/id/${state.id}`,
                            type: 'GET',
                        }, function (ret, res) {
                            form.model = res.data;
                            return false
                        }, function (ret, res) { })
                    }

                    function onConfirm() {
                        proxy.$refs['formRef'].validate((valid) => {
                            if (valid) {
                                Fast.api.ajax({
                                    url: state.type == 'add' ? 'sum/trade/rule/add' : `sum/trade/rule/edit/id/${state.id}`,
                                    type: 'POST',
                                    data: form.model,
                                }, function (ret, res) {
                                    Fast.api.close()
                                }, function (ret, res) { })
                            }
                        });
                    }

                    onMounted(() => {
                        getLanguageOption();
                        state.type == 'edit' && getDetail()
                    })

                    return {
                        state,
                        form,
                        language,
                        getLanguageOption,
                        modelTitle,
                        onConfirm,
                    }
                }
            }
            createApp('addEdit', addEdit);
        }
    };
    return Controller;
});
